<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户编号" prop="customerNumber">
        <el-input
          v-model="queryParams.customerNumber"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <!-- 新增导入按钮 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain icon="el-icon-upload2"
          size="mini"
          @click="handleImport">导入
        </el-button>
      </el-col>
      <!-- 新增导出按钮 -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="客户编号" align="center" prop="customerNumber"/>
      <el-table-column label="客户名称" align="center" prop="customerName"/>
      <el-table-column label="所属行业" align="center" prop="industry"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'warning'">
            {{ statusFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="联系人姓名" align="center" prop="contactName"/>
      <el-table-column label="手机号码" align="center" prop="phoneNumber"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-address"
            @click="handleAddress(scope.row)"
          >地址
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--上传execl弹窗-->
    <!--弹窗区域-->
    <el-dialog title="导入" :visible.sync="importDialog" width="450px">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :file-list="fileList"
        :before-upload="beforeUpload"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>

    </el-dialog>


    <!-- 添加或修改客户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="customerNumber">
              <el-input v-model="form.customerNumber" placeholder="请输入客户编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-input v-model="form.industry" placeholder="请输入所属行业"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%"
                         @change="handleStatusChange">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from '@/utils/auth' // 若依框架默认的token工具函数
import {
  listCustomer,
  getCustomer,
  addCustomer,
  updateCustomer,
  delCustomer,
  importTemplate, uploadExcel
} from "@/api/tms/base/customer";
import * as XLSX from 'xlsx';

export default {
  name: "Customer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 导入相关变量
      importDialog: false,
      file: null,
      fileList: [],
      upload: {
        headers: {Authorization: "Bearer " + getToken()}
      },
      // 状态数据字典
      statusOptions: [
        {value: "0", label: "启用"},
        {value: "1", label: "停用"}
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerNumber: undefined,
        customerName: undefined,
        phoneNumber: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerNumber: [
          {required: true, message: "客户编号不能为空", trigger: "blur"}
        ],
        customerName: [
          {required: true, message: "客户名称不能为空", trigger: "blur"}
        ],
        industry: [
          {required: true, message: "所属行业不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ],
        contactName: [
          {required: true, message: "联系人姓名不能为空", trigger: "blur"}
        ],
        phoneNumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    // 上传前的回调，用于清空上次上传的文件列表
    beforeUpload(file) {
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    uploadExcelFun() {
      const file = this.file;
      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file
      // 封装的上传文件方法
      uploadExcel(formData).then((res) => {
        console.log("上传成功", res);
        this.$message({
          message: "上传成功",
          type: "success",
        });
        // 上传成功后添加到文件列表
        this.fileList.push({
          name: file.name,
        }); // 上传成功后添加到文件列表
        this.uploadExcelDialog = false; // 关闭弹窗
        this.pageNum = 1; // 刷新列表
        this.getList(); // 刷新列表
      });
    },
    // 监听文件改变
    handleChange(file) {
      console.log("file", file)
      this.file = file.raw;
    },


    /** 查询客户信息列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 状态显示转换
    statusFormat(row) {
      const statusMap = {
        "0": "启用",
        "1": "停用"
      };
      return statusMap[row.status] || "未知状态";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },
    /** 地址按钮操作 */
    handleAddress(row) {
      // 使用name进行路由跳转
      this.$router.push({
        name: 'Address',
        query: {customerId: row.id}
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(() => {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        customerNumber: null,
        customerName: null,
        industry: null,
        status: null,
        contactName: null,
        phoneNumber: null
      };
      this.resetForm("form");
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 状态改变处理 */
    handleStatusChange(value) {
      console.log("状态改变为:", value);
    },


    /** 导入按钮操作 */
    handleImport() {
      this.importDialog = true;
    },

    /** 导出按钮操作 */
    handleExport() {
      // 使用前端数据导出，不依赖后端接口
      this.$confirm('确定要导出客户数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        try {
          // 准备导出的数据，只包含需要的字段
          const exportData = this.customerList.map(row => ({
            '客户编号': row.customerNumber,
            '客户名称': row.customerName,
            '所属行业': row.industry,
            '状态': row.status,
            '联系人姓名': row.contactName,
            '手机号码': row.phoneNumber,
            '创建时间': row.createTime
          }));

          // 创建工作簿
          const ws = XLSX.utils.json_to_sheet(exportData);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '客户数据');

          // 导出文件
          XLSX.writeFile(wb, '客户数据.xlsx');

          this.$modal.msgSuccess('导出成功');
        } catch (error) {
          console.error('导出失败:', error);
          this.$modal.msgError('导出失败');
        }
      }).catch(() => {
      });
    },

  }
};
</script>

<style scoped>
.el-button + .el-button {
  margin-left: 5px;
}
</style>

